<template>
  <div style="width:100%; height:800px; background:#ffffff">
    <div class="login-img">
      <img alt="logo" class="loginImg" style="float:left;position:relative;top:80px;padding-left:200px" src="../../assets/img/loginImg.png" />
    </div>
    <div class="login-form" style="width:500px;float:right;margin-left:20px;margin-top:80px;margin-right:50px">
      <div class="top">
        <div class="header" style="height:80px;line-height:44px;text-align:center;padding-right:40px;">
          <img alt="logo" class="logo" style="height: 60px;margin-top:-10px;padding-right:50px;" src="../../assets/img/logo.png" />
          <span class="title" style="font-size:33px;font-family:'Myriad Pro','Helvetica Neue',Arial,Helvetica,sans-serif;font-weight:600;position:relative;top:2px;line-height:84px;">基础开发平台</span>
        </div>
      </div>
      <a-form :form="form" class="user-layout-login" ref="formLogin" id="formLogin">
        <a-tabs
          :activeKey="customActiveKey"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        >
          <a-tab-pane key="tab1" tab="账号密码登录">
            <a-form-item>
              <a-input
                v-bind:disabled="diasabledInput"
                size="large"
                v-decorator="['username',validatorRules.username,{ validator: this.handleUsernameOrEmail }]"
                type="text"
                placeholder="请输入帐户名 / admin">
                <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-item>

            <a-form-item>
              <a-input
                v-decorator="['password',validatorRules.password]"
                size="large"
                type="password"
                autocomplete="false"
                placeholder="密码 / 123456">
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-item>

            <a-row :gutter="0">
              <a-col :span="16">
                <a-form-item>
                  <a-input
                    v-decorator="['inputCode',validatorRules.inputCode]"
                    size="large"
                    type="text"
                    @change="inputCodeChange"
                    placeholder="请输入验证码">
                    <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8" style="text-align: right">
                <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
                <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
              </a-col>
            </a-row>


          </a-tab-pane>
        </a-tabs>

        <a-form-item style="margin-top:24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            style="width: 100%"
            :loading="loginBtn"
            @click.stop.prevent="handleSubmit"
            :disabled="loginBtn">确定
          </a-button>
        </a-form-item>
      </a-form>

    </div>
  </div>
</template>

<script>
  import {IA300_GetName,IA300_GetLastError,createElementIA300,DetectIA300Plugin,IA300_CheckExist,IA300_CheckPassword,IA300_GetHardwareId,IA300_CalculateClientHash,IA300_GetOther} from '@/utils/IA300ClientJavascript.js';
  import { mapActions } from "vuex"
  import { getAction } from '@/api/manage'
  import UserLayout from '@/components/layouts/UserLayout'
  export default {
    components: {
      UserLayout
    },
    data () {
      return {
        customActiveKey: "tab1",
        diasabledInput:false,
        flag:false,
        ukeyId:"",
        ClientDigest:"",
        randomMessageFromServer:"",
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        requiredTwoStepCaptcha: false,
        stepCaptchaVisible: false,
        form: this.$form.createForm(this),
        encryptedString:{
          key:"",
          iv:"",
        },
        state: {
          time: 60,
          smsSendBtn: false,
        },
        validatorRules:{
          username:{rules: [{ required: true, message: '请输入用户名!'},{validator: this.handleUsernameOrEmail}]},
          password:{rules: [{ required: true, message: '请输入密码!',validator: 'click'}]},
          inputCode:{rules: [{ required: true, message: '请输入验证码!'}]}
        },
        verifiedCode:"",
        inputCodeContent:"",
        inputCodeNull:true,
        currentUsername:"",
        currdatetime:'',
        randCodeImage:'',
        requestCodeSuccess:false,
      }
    },
    created () {
      this.getNeedData();
      this.ukeyCheck();
      this.currdatetime = new Date().getTime();
      this.handleChangeCheckCode();
      // update-begin- --- author:scott ------ date:20190805 ---- for:密码加密逻辑暂时注释掉，有点问题
      //this.getEncrypte();
      // update-end- --- author:scott ------ date:20190805 ---- for:密码加密逻辑暂时注释掉，有点问题
    },
    methods: {
      ...mapActions(['Login', 'Logout', 'PhoneLogin']),
      getNeedData(){
        getAction(`/demo/LoginDemo/getNeedData`).then(res=>{
          if(res.success){
            this.randomMessageFromServer = res.result.Random;
            //randomMessageFromServer
          }else{
            console.log(res.message);
          }
        })
      },
      ukeyCheck(){
        //定时检查ukey是否被拔出
        //IA300_StartCheckTimer(5000,"UKEY已从设备中移出","${ctx}/views/login-iakey.jsp",1);
        createElementIA300() //对本页面加入IA300插件
        //DetectActiveX() 判断IA300Clinet是否安装
        var create = DetectIA300Plugin();
        if (create == false) {
          this.$message.error("UKEY插件未安装!");
          return false;
        }
        if(IA300_CheckExist()>=1){
          this.flag = true;
        }
        if(this.flag){
          var name = IA300_GetName();
          if(name == null || name == ''){
            name = IA300_GetOther();
            if(name == null || name == ''){
              name = '已从设备读取';
            }
          }
          this.$nextTick(() => {
            this.diasabledInput=true;
            this.form.setFieldsValue({
              'username':name
            })
          });
        }else{
          this.$message.error("未找到UKEY!请检查是否与其他软件冲突造成系统未识别");
          return false;
        }
      },
      // handler
      handleUsernameOrEmail (rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      handleSubmit () {
        let that = this
        let loginParams = {};
        that.loginBtn = true;
        // 使用账户密码登录
        that.form.validateFields([ 'username', 'password','inputCode', 'rememberMe' ], { force: true }, (err, values) => {
          if (!err) {
            loginParams.username = values.username
            // update-begin- --- author:scott ------ date:20190805 ---- for:密码加密逻辑暂时注释掉，有点问题
            //loginParams.password = md5(values.password)
            //loginParams.password = encryption(values.password,that.encryptedString.key,that.encryptedString.iv)





            if (this.flag) {
              //获取页面文本框的密码
              const password = this.form.getFieldValue('password');
              if (password == "") {
                this.$message.error("密码不能为空")
                this.loginBtn = false;
                return false;
              }
              //检测IA300是否存在
              if (IA300_CheckExist() < 1) {
                this.$message.error("未找到UKEY,请插上UKEY后再点击登录!");
                this.loginBtn = false;
                return false;
              }
              //打开USB Key,sIAPWD为USB Key的用户密码
              var retVal = IA300_CheckPassword(password);
              if (retVal != 0) {
                //IA300_GetLastError 为封装到JS文件的获取错误信息的方法,返回错误信息,根据错误信息到帮助文档查询具体错误.<br/>如果您忘记密码，请点击【重置密码】按钮，重置您的登录密码

                this.$message.error("您输入的密码不正确，请重新输入。");
                this.form.setFieldsValue({"password":""});
                this.loginBtn = false;
                return false;
              } else {
                //获取本Key的唯一硬件ID
                var ukeyId = IA300_GetHardwareId();
                if (ukeyId == "") {
                  this.$message.error("获取UKEY硬件ID失败，错误码：" + IA300_GetLastError());
                  this.loginBtn = false;
                }
                this.ukeyId = ukeyId
                //获得随机数
                //进行客户端摘要的计算，randomMessageFromServer为随机数，可随机长度
                var ClientDigest = IA300_CalculateClientHash(this.randomMessageFromServer);
                if (ClientDigest != "") {
                  this.ClientDigest = ClientDigest;
                  //return true;
                } else {
                  this.$message.error("UKEY计算摘要失败，错误码：" + IA300_GetLastError());
                  this.loginBtn = false;
                  return false;
                }
              }
            }

            loginParams.password = values.password
            //loginParams.remember_me = values.rememberMe
            // update-begin- --- author:scott ------ date:20190805 ---- for:密码加密逻辑暂时注释掉，有点问题
            loginParams.captcha = that.inputCodeContent
            loginParams.checkKey = that.currdatetime
            loginParams.ukeyId = that.ukeyId;
            loginParams.ClientDigest = that.ClientDigest;
            console.log("登录参数",loginParams)
            this.login(loginParams)
          }else {
            that.loginBtn = false;
          }
        })
      },
      login(loginParams) {
        getAction(`/demo/LoginDemo/ukeyLogin`,loginParams).then(res=>{
          console.log(res);
          if(res.success){
            this.$message.success(res.message);
          }else{
            this.$message.error(res.message);
          }
          this.loginBtn = false;
        })
      },
      handleChangeCheckCode(){
        this.currdatetime = new Date().getTime();
        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            this.randCodeImage = res.result
            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })
      },
      inputCodeChange(e){
        this.inputCodeContent = e.target.value
      }
    }
  }
</script>
<style lang="less" scoped>
  .login-form{
    width: 500px;
    float: right;
    margin-left: 20px;
  }
  .ant-form{
    width: 500px;
    float: right;
    padding: 0 30px;
    .ant-tabs-content-animated{
      margin-top: 20px !important;
    }
  }
  .loginImg{
    float: left;
    position: relative;
    top: -30px;
  }
  .ant-tabs-tabpane{
    padding: 15px 0 0;
  }
  .top {
    text-align: center;
    .header {
      height: 80px;
      line-height: 44px;
      text-align: center;
      padding-right: 40px;
      a {
        text-decoration: none;
      }
      .logo {
        height: 60px;
        margin-top: -10px;
        padding-right: 20px;
      }
      .title {
        font-size: 33px;
        font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
        line-height: 84px;
      }
    }
    .desc {
      font-size: 14px;
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }
  .icon {
    font-size: 24px;
    margin-left: 16px;
    vertical-align: middle;
    cursor: pointer;
    transition: color 0.3s;
  }
  .login-button{
    width: 100%
  }
  .valid-error .ant-select-selection__placeholder{
    color: #f5222d;
  }
  .footer[data-v-623770b4]{
    background: #fff !important;
    box-shadow: 0 0 4px 0 rgba(0,0,0,0.2);
  }
</style>